package com.taxi.driver.module.main;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;

import com.qianxx.utils.RxUtil;
import com.qianxx.utils.ToastUtil;
import com.socks.library.KLog;
import com.taxi.driver.R;
import com.taxi.driver.common.AppController;
import com.taxi.driver.common.Application;
import com.taxi.driver.common.BaseActivity;
import com.taxi.driver.data.config.ConfigRepository;
import com.taxi.driver.data.entity.ConfigEntity;
import com.taxi.driver.data.user.UserRepository;
import com.taxi.driver.event.NetworkEvent;
import com.taxi.driver.event.UserEvent;
import com.taxi.driver.module.login.LoginActivity;
import com.taxi.driver.module.main.mine.setting.volume.SystemVolumeRceiver;
import com.taxi.driver.socket.SocketData;
import com.taxi.driver.socket.SocketEvent;
import com.taxi.driver.socket.SocketService;
import com.taxi.driver.util.SpeechUtil;
import com.taxi.driver.widget.dialog.ConfirmDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Observable;

public class MainActivity extends BaseActivity {

    @BindView(R.id.vp_main)
    ViewPager mVpMain;
    @BindView(R.id.tab_main)
    TabLayout mTabMain;

    @Inject
    UserRepository mUserRepository;

    @Inject
    ConfigRepository mConfigRepository;

    private NetworkChangeReceiver mReceiver;
    private SystemVolumeRceiver mSystemVolumeRceiver;
    private volatile boolean mExitFlag = false;
    private Dialog mConfirmDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        Application.getAppComponent().inject(this);
        // 初始化讯飞语音
        SpeechUtil.init(this.getApplicationContext(), getResources().getString(R.string.xfyun_id), mUserRepository);

        mVpMain.setAdapter(new MainPagerAdapter(getSupportFragmentManager(), this));
        mTabMain.setupWithViewPager(mVpMain);
        mVpMain.setOffscreenPageLimit(2);
        mVpMain.setCurrentItem(1); //先显示HomeFragment
        mTabMain.getTabAt(1).setCustomView(R.layout.layout_center_title); //设置中间Title的布局

        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fl_main_duty);
        if (fragment == null)
            addFragment(R.id.fl_main_duty, AppController.getHomeBtnFragment());

        EventBus.getDefault().register(this);
        // 注册网络和系统音量监听广播
        register();
        // 获取所有H5页面的路径
        getH5Config();
        // 延时检测网络
//        new Handler().postDelayed(this::checkNetwork, 800);//注册广播监听,不用实时监听,会发生错误
    }

    @Override
    protected void onResume() {
        if (mUserRepository.getScreenStatue()) {
            bright();
        } else {
            cancelBright();
        }
        super.onResume();
        /* 开启长连接 */
        if (mUserRepository.isLogin())
            EventBus.getDefault().post(new SocketEvent(SocketEvent.CONNECT));
    }

    @Override
    public int getBarColor() {
        return R.color.theme_color;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUserEvent(UserEvent userEvent) {
        switch (userEvent.type) {
            case UserEvent.LOGOUT:
                finish();
                break;
            case UserEvent.ACCOUNT_WAS_CREATED:
                SocketData data = (SocketData) userEvent.obj1;
                String title = data == null ? "封号" : data.title;
                String details = data == null ? "账号被封" : data.content;
                if (mConfirmDialog != null) {
                    return;
                }
                mConfirmDialog = new ConfirmDialog(this, title, details, "确认")
                        .setConfirmClickListener(dialog -> {
                            dialog.dismiss();
                            mConfirmDialog = null;
                            mUserRepository.logout();
                            LoginActivity.start(this);
                        });
                mConfirmDialog.show();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        cancelBright();
        unregister();
        // 关闭Socket服务
        SocketService.stopService(this);
    }

    /**
     * 注册网广播
     */
    public void register() {
        // 网络监听广播
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        mReceiver = new NetworkChangeReceiver();
        registerReceiver(mReceiver, filter);

        // 音量广播
        IntentFilter filter2 = new IntentFilter("android.media.VOLUME_CHANGED_ACTION");
        mSystemVolumeRceiver = new SystemVolumeRceiver();
        registerReceiver(mSystemVolumeRceiver, filter2);
    }

    /**
     * 注销广播
     */
    public void unregister() {
        if (mReceiver != null)
            unregisterReceiver(mReceiver);

        if (mSystemVolumeRceiver != null)
            unregisterReceiver(mSystemVolumeRceiver);
    }

    /**
     * 监听网络变化
     */
    class NetworkChangeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            checkNetwork();
        }
    }

    /**
     * 检查网络状态
     */
    private void checkNetwork() {
        ConnectivityManager connectivityManager = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        boolean networkAvailable = networkInfo != null && networkInfo.isAvailable();
        mUserRepository.setNetworkStatus(!networkAvailable);
        if (networkAvailable) {
            EventBus.getDefault().post(new NetworkEvent(NetworkEvent.CONNECT));
        } else {
            EventBus.getDefault().post(new NetworkEvent(NetworkEvent.DISCONNECT));
        }
    }

    /**
     * 获取所有H5页面的路径
     */
    public void getH5Config() {
        mConfigRepository.variable()
                .compose(RxUtil.applySchedulers())
                .subscribe(entitys -> {
                    for (ConfigEntity entity : entitys) {
                        if (entity.key.equals("about"))
                            mConfigRepository.saveAbout(entity.valule);
                        if (entity.key.equals("priceRules"))
                            mConfigRepository.savePriceRules(entity.valule);
                        if (entity.key.equals("ruleExplain"))
                            mConfigRepository.saveRuleExplain(entity.valule);
                        if (entity.key.equals("userAgreement"))
                            mConfigRepository.saveAgress(entity.valule);
                    }
                }, KLog::e);
    }

    @Override
    public void onBackPressed() {
        if (mExitFlag) {
            finish();
        } else {
            mExitFlag = true;
            ToastUtil.getInstance().toast("再次点击退出应用");
            Observable.timer(2, TimeUnit.SECONDS)
                    .subscribe(aLong -> mExitFlag = false,
                            KLog::e);
        }
    }
}
